package com.qen.socket.nio

import cn.hutool.core.io.BufferUtil
import cn.hutool.core.io.IoUtil
import cn.hutool.core.lang.Console
import cn.hutool.core.util.StrUtil
import cn.hutool.socket.nio.NioServer
import java.nio.ByteBuffer
import java.nio.channels.SocketChannel

fun main() {
    val set = mutableSetOf<SocketChannel>()
    val server = NioServer(8080)
    server.setChannelHandler { sc ->
        set.add(sc)
        val readBuffer = ByteBuffer.allocate(1024)
        val readBytes = sc.read(readBuffer)
        if (readBytes > 0) {
            readBuffer.flip()
            val bytes = ByteArray(readBuffer.remaining())
            readBuffer.get(bytes)
            val body = StrUtil.utf8Str(bytes)
            Console.log("[${sc.remoteAddress}]:${body}")
//            for (s in set) {
//                doWrite(s, "广播" + body)
//            }
            doWrite(sc, body)
        } else {
            IoUtil.close(sc)
        }
    }
    server.listen()
}

fun doWrite(channel: SocketChannel, response: String) {
    val resp = "收到消息${response}"
    channel.write(BufferUtil.createUtf8(resp))
}